package com.amazon.trietree.server;

import com.amazon.trietree.dedupstruct.CuckooHashMap;
import com.amazon.trietree.fingerprint.FingerPrint;
import com.amazon.trietree.fingerprint.FingerPrintFileContainer;
import com.amazon.trietree.io.FingerPrintIOInterface;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Tylaar
 * Date: 11/7/12
 * Time: 11:38 PM
 * Company: Amazon.com
 */
public class MetaDataLocalServer {
    private CuckooHashMap<String, Integer> cuckooHashMap;
    private FingerPrintIOInterface ioInterface;
    private MetaDataStructMonitor monitor;
    private int prefixLength;
    private int lineNum = 0;

    public MetaDataStructMonitor getMonitor() {
        return monitor;
    }

    public void setMonitor(MetaDataStructMonitor monitor) {
        this.monitor = monitor;
    }

    public CuckooHashMap<String, Integer> getCuckooHashMap() {
        return cuckooHashMap;
    }

    public void setCuckooHashMap(CuckooHashMap<String, Integer> cuckooHashMap) {
        this.cuckooHashMap = cuckooHashMap;
    }

    public FingerPrintIOInterface getIoInterface() {
        return ioInterface;
    }

    public void setIoInterface(FingerPrintIOInterface ioInterface) {
        this.ioInterface = ioInterface;
    }

    public int getPrefixLength() {
        return prefixLength;
    }

    public void setPrefixLength(int prefixLength) {
        this.prefixLength = prefixLength;
    }

    public boolean addSingleFileFingerPrintsFromIO(){
        lineNum++;
        if(lineNum % 10 == 0)
            System.out.println("linenum:" + lineNum);
        FingerPrintFileContainer container = null;
        container = ioInterface.readSingleTrackFromStream();
        if(container == null)return false;
        else{
            insertIntoCuckooHash(container);
            return true;
        }
    }

    private void insertIntoCuckooHash(FingerPrintFileContainer container) {
        List<FingerPrint> fps = container.getFingerprintList();
        monitor.increaseTotalCountBy(container.getFingerprintNum());
        for(FingerPrint fp : fps){
            String prefixFp = fp.getHexFingerPrint().substring(0, prefixLength);

            if(cuckooHashMap.containsKey(prefixFp)){
                int oldCount = cuckooHashMap.get(prefixFp);
                cuckooHashMap.put(prefixFp,oldCount+1);

            }
            else{
                cuckooHashMap.put(prefixFp, 1);
                monitor.increaseTableSizeByOne();
            }
        }
    }

    public void addAllFingerPrintsFromIO(){
        boolean hasMore;
        do{
            hasMore = addSingleFileFingerPrintsFromIO();
        }while(hasMore);
    }
}
